#!/usr/bin/python3
# -*- coding: UTF-8 -*-
import sys
import os
from pathlib import Path
from parsing import parsing

def upgrade_url(file, new_url):
    upgrade_spec(file, "URL:", new_url)

def upgrade_source0(file, source0):
    upgrade_spec(file, "Source0:", source0)
def upgrade_spec(file, old_str, new_str):
    file_data = ""
    with open(file, "r", encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = old_str + "\t\t" + new_str + "\n"
            file_data += line
    with open(file,"w",encoding="utf-8") as f:
        f.write(file_data)
    
if __name__ == "__main__":

    dft_root_path = os.path.join(str(Path.home()))

    parser = parsing.do_args(dft_root_path)

    args = parser.parse_args()        

    if args.mode=="create":
        porter = parsing.porter_creator(args)
        if porter is None:
            print("Type %s is not supported now\n" % args.type)
            sys.exit(1)

        if args.requires:
            req_list = porter.get_build_requires()
            if req_list is not None:
                for req in req_list:
                    print(req)
        elif args.rpm:
            req_list = porter.get_dependencies_rpm()
            if req_list is not None:
                for req in req_list:
                    print(req)
        elif args.build:
            ret = parsing.build_rpm(porter, args.pom, dft_root_path)
            if ret != "":
                print("build failed : BuildRequire : %s\n" % ret)
                sys.exit(1)
        elif args.buildinstall:
            ret = parsing.build_install_rpm(porter, args.pom, dft_root_path)
            if ret != "":
                print("Build & install failed\n")
                sys.exit(1)
        else:
            parsing.build_spec(porter, args.output)
    elif args.mode=="upgrade":
        if args.url != "":
            upgrade_url(args.spec, args.url)
        if args.source0 != "":
            upgrade_source0(args.spec, args.source0)
    else:
        print("mode %s is not supported now\n" % args.mode)
        sys.exit(1)

